const db = require('../config/db');
const { success, fail } = require('../utils/response');

// 统一图片字段：后端一律存储为 JSON 数组字符串；无图存空字符串
function normalizeImageField(image) {
  if (image === undefined || image === null) return '';
  if (typeof image !== 'string') return '';
  const trimmed = image.trim();
  if (trimmed.length === 0) return '';
  if (trimmed.startsWith('[')) {
    // 已是 JSON 数组字符串，直接使用
    return trimmed;
  }
  if (trimmed.includes(',')) {
    // 逗号分隔转 JSON 数组字符串
    const arr = trimmed.split(',').map(s => s.trim()).filter(Boolean);
    return JSON.stringify(arr);
  }
  // 单值转 JSON 数组字符串
  return JSON.stringify([trimmed]);
}

// controllers/message.js 中的 getMessages 方法
exports.getMessages = async (req, res) => {
  const [rows] = await db.query(`
    SELECT message.*, User.username, User.avatar 
    FROM message 
    JOIN User ON message.user_id = User.id 
    ORDER BY publish_date DESC
  `);
  res.json(success(rows));
};

exports.createMessage = async (req, res) => {
  const { content, image } = req.body;
  if (!content) return res.json(fail('留言内容不能为空'));
  
  const normalizedImage = normalizeImageField(image);
  await db.query('INSERT INTO message (user_id, content, image, publish_date) VALUES (?, ?, ?, NOW())', [req.user.id, content, normalizedImage]);
  res.json(success());
};

// 修复：补充 try/catch，移除未使用的 content/image 解构，统一小写表名
exports.updateMessageImage = async (req, res) => {
  try {
    const { id } = req.params;

    // 检查留言是否存在且属于当前用户
    const [rows] = await db.query('SELECT id FROM message WHERE id=? AND user_id=?', [id, req.user.id]);
    if (!rows.length) return res.json(fail('留言不存在或无权限修改'));

    if (!req.file) return res.json(fail('请选择要上传的图片'));

    const fs = require('fs');
    const mime = req.file.mimetype || 'image/jpeg';
    const base64 = fs.readFileSync(req.file.path, { encoding: 'base64' });
    const dataUri = `data:${mime};base64,${base64}`;

    // 单图也统一存为 JSON 数组字符串
    const normalizedImage = JSON.stringify([dataUri]);
    await db.query('UPDATE message SET image=?, publish_date=NOW() WHERE id=?', [normalizedImage, id]);

    // 删除临时文件
    fs.unlink(req.file.path, () => {});

    res.json(success({ image: normalizedImage }));
  } catch (error) {
    // 清理临时文件
    if (req.file) {
      const fs = require('fs');
      fs.unlink(req.file.path, () => {});
    }
    res.json(fail(error.message || '更新图片失败'));
  }
};

exports.updateMessage = async (req, res) => {
  const { id } = req.params;
  const { content, image } = req.body;

  // 检查留言是否存在且属于当前用户
  const [rows] = await db.query('SELECT id FROM message WHERE id=? AND user_id=?', [id, req.user.id]);
  if (!rows.length) return res.json(fail('留言不存在或无权限修改'));

  // 动态构造更新字段：只更新传入的字段
  const updateFields = [];
  const values = [];

  if (content !== undefined) {
    updateFields.push('content = ?');
    values.push(content);
  }
  if (image !== undefined) {
    const normalizedImage = normalizeImageField(image);
    updateFields.push('image = ?');
    values.push(normalizedImage);
  }
  if (updateFields.length === 0) {
    return res.json(fail('没有需要更新的字段'));
  }

  // 刷新发布时间
  updateFields.push('publish_date = NOW()');

  values.push(id);
  const sql = `UPDATE message SET ${updateFields.join(', ')} WHERE id=?`;
  await db.query(sql, values);

  res.json(success());
};

exports.deleteMessage = async (req, res) => {
  const { id } = req.params;
  
  // 检查留言是否存在且属于当前用户
  const [rows] = await db.query('SELECT id FROM message WHERE id=? AND user_id=?', [id, req.user.id]);
  if (!rows.length) return res.json(fail('留言不存在或无权限删除'));
  
  await db.query('DELETE FROM message WHERE id=?', [id]);
  res.json(success());
};